<?php

namespace App\Admin\Actions\Post;

use App\Models\Cart;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;

class JoinPrimary extends BatchAction
{
    public $name = '加入预选';

    public function handle(Collection $collection)
    {
        foreach ($collection as $model) {

            if (isset($model->isbn13)) {
                $isbn = $model->isbn13;
                $img = $model->getImageUrl();
            } else {
                $isbn = $model->isbn;
                $img = $model->img_url;
            }

            $cart = Cart::where('isbn', $isbn)->first();
            if (!$cart) {
                $data = [
                    'title' => $model->title,
                    'isbn' => $isbn,
                    'image' => $img,
                ];
                Cart::insert($data);
            }
        }

        return $this->response()->success('操作成功')->refresh();
    }

}
